package com.apexsoft.front.common.plugins.filter.impl;

import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.plugins.filter.IFilter;
import com.apexsoft.front.common.plugins.filter.annotation.AFilter;
import com.apexsoft.front.common.utils.JsonResult;
import com.apexsoft.front.common.utils.session.UserSessionNoRedis;
import com.apexsoft.monitor.common.MonitorConstant;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@AFilter(name="manager auth Filter")
public class ManagerAuthFilter implements IFilter {
	
	private static final Logger log = LogManager.getRootLogger();

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Exception {
		String requestURI = request.getRequestURI();
		String contextPath = request.getServletContext().getContextPath();
		String requestPath = requestURI.substring(contextPath.length());
		String sessionId = request.getRequestedSessionId();
		requestPath = formatRequestURI(requestPath);
		log.debug("\n当前请求action:"+requestURI+";当前的SessionId："+sessionId);
		JSONObject userInfo = UserSessionNoRedis.getSessionObj(request, UserSessionNoRedis.CONSOLE_SESSION);
		if (userInfo != null) {
			boolean permission = false;
			for (String url : MonitorConstant.crudReqMappingList){
				if (requestPath.equals(url)){
					permission = true;
					break;
				}
			}
			if (permission){
				String userAttr = userInfo.getString("attr");
				JSONObject attrJson = StringUtils.isNotBlank(userAttr)?JSONObject.parseObject(userAttr):new JSONObject();
				if (attrJson.getIntValue("editable")!=1){
					permission(request,response,requestPath);
				}
			}
		}
		return true;
	}

	/**
	 * 超时处理
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void permission(HttpServletRequest request, HttpServletResponse response, String requestPath) throws Exception {
		String requestType = request.getHeader("X-Requested-With"); // XMLHttpRequest
		if ("XMLHttpRequest".equals(requestType)) {// 异步请求
			PrintWriter out = null;
			response.setContentType("text/html;charset=UTF-8");
			try {
				out = response.getWriter();
				response.setStatus(912);// 超时标记
				JSONObject result = new JsonResult(false, "没有操作权限").getResult();
				result.put("code",-1);
				out.println(result.toString());
			} catch (Exception e) {
				log.error(e.getMessage());
			} finally {
				out.close();
			}
		} else {// 直接请求
			request.getRequestDispatcher("/permission").forward(request, response);
		}
	}


	/**
	 * 去除访问地址串中多余的的斜杠，防止绕过过滤器
	 * 
	 * @param uri
	 * @return
	 */
	private String formatRequestURI(String uri) {
		String[] s = uri.split("/");
		StringBuffer result = new StringBuffer();
		for (String c : s) {
			if (!"".equals(c.trim()))
				result.append("/").append(c);
		}
		return result.toString();
	}

}
